// 帖子和二手可以共用这个评论
import mongoose from 'mongoose';
import moment from 'moment';
import db from './db';
mongoose.Promise = global.Promise;

const GoodSchema = new mongoose.Schema({
    name: String, // 商品名
    point: Number, // 积分数
    url: String, // 商品图片
    desc: String,
    range: String, // eg. 2018-10-08至2018-10-20
    createTime: Number,
});

GoodSchema.methods.saveGood = function (good, cb) {
    good.createTime = moment().unix();
    this.model('good').insertMany([good], cb);
};

GoodSchema.methods.getGoods = function (query, cb) {
    const { current, pageSize, ...leftQuery } = query;
    const goodModel = this.model('good');
    goodModel.count(leftQuery, function (err, count) {
        const hasMore = count / pageSize > current;
        goodModel.find(leftQuery).sort({createTime: -1}).skip((current - 1) * pageSize).limit(pageSize).exec((err, goods) => cb(err, goods, count, hasMore));
    });
};

GoodSchema.methods.getAllGoods = function (query, cb) {
    this.model('good').find(query, { _id: 0 }, cb);
};

GoodSchema.methods.getGood = function (query, cb) {
    this.model('good').findOne(query, cb);
};

GoodSchema.methods.updateGood = function (good, cb) {
    const _id = good._id;
    delete good._id;
    this.model('good').findOneAndUpdate({ _id }, { $set: good }, cb);
};

GoodSchema.methods.removeGoods = function (goodIds, cb) {
    this.model('good').remove({ _id: { $in: goodIds } }, cb);
};

export default db.model('good', GoodSchema);